package com.gaokuo.es.property;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * PropertyUtil
 * 字段名称工具
 *
 * @author gk  网络
 * @date 2021/4/22 11:22
 */
public class PropertyNameUtil {


    /**
     * 获取类全部字段  包含父类
     * @param clazz ~
     * @return String of Array
     */
    public static String[] getAllFieldName(Class<?> clazz){
        Class<?> focusClass = clazz;
        List<Field> fields = new ArrayList<>();
        while (focusClass != null){
            fields.addAll(Arrays.asList(focusClass.getDeclaredFields()));
            focusClass = focusClass.getSuperclass();
        }
        return fields.stream().map(Field::getName).toArray(String[]::new);
    }
    /**
     * 获取类全部字段  包含父类
     * @param clazz ~
     * @return Field of List
     */
    public static List<Field> getAllField(Class<?> clazz){
        Class<?> focusClass = clazz;
        List<Field> fields = new LinkedList<>();
        while (focusClass != null){
            fields.addAll(Arrays.asList(focusClass.getDeclaredFields()));
            focusClass = focusClass.getSuperclass();
        }
        return fields;
    }

    /**
     * 下划线转驼峰
     * user_name  ---->  userName
     * userName   --->  userName
     *
     * @param underlineStr 带有下划线的字符串
     * @return 驼峰字符串
     */
    public static String toCamelCase(String underlineStr) {
        if (underlineStr == null) {
            return null;
        }
        // 分成数组
        char[] charArray = underlineStr.toCharArray();
        // 判断上次循环的字符是否是"_"
        boolean underlineBefore = false;
        StringBuilder buffer = new StringBuilder();
        for (int i = 0, l = charArray.length; i < l; i++) {
            // 判断当前字符是否是"_",如果跳出本次循环
            if (charArray[i] == 95) {
                underlineBefore = true;
            } else if (underlineBefore) {
                // 如果为true，代表上次的字符是"_",当前字符需要转成大写
                buffer.append(charArray[i] -= 32);
                underlineBefore = false;
            } else {
                // 不是"_"后的字符就直接追加
                buffer.append(charArray[i]);
            }
        }
        return buffer.toString();
    }

    /**
     * 驼峰转 下划线
     * userName  ---->  user_name
     * user_name  ---->  user_name
     *
     * @param camelCaseStr 驼峰字符串
     * @return 带下滑线的String
     */
    public static String toUnderlineCase(String camelCaseStr) {
        if (camelCaseStr == null) {
            return null;
        }
        // 将驼峰字符串转换成数组
        char[] charArray = camelCaseStr.toCharArray();
        StringBuilder buffer = new StringBuilder();
        //处理字符串
        for (int i = 0, l = charArray.length; i < l; i++) {
            if (charArray[i] >= 65 && charArray[i] <= 90) {
                buffer.append("_").append(charArray[i] += 32);
            } else {
                buffer.append(charArray[i]);
            }
        }
        return buffer.toString();
    }
}
